from django.db.models import F
from django.http import Http404
from django.shortcuts import redirect, get_object_or_404
from django.contrib import messages

from core.extensions.decorators import login_required

from core.models import Event, User, Participation
from core.views.event.details import details
from core.views.event.strategies_calculation import get_current_sum_for_user


@login_required()
def leave(request, id):
    event = get_object_or_404(Event, id=id)
    user = User.objects.get(id=request.session['user_id'])
    if user not in event.participants.all() \
        or event.status != Event.Status.Scheduled:
        raise Http404()
    participation = Participation.objects.get(user=user, event=event)
    investment = participation.investment
    patron = participation.patron
    participation.delete()
    event.current_sum = F('current_sum') - investment
    strategy = event.strategy.id
    event.current_sum_for_user = get_current_sum_for_user(id, strategy, investment, patron) 
    event.save()
    messages.info(request, 'left')
    return redirect(details, id)
